import React, { useContext, useEffect, useRef, useState } from 'react'
import { Table, Button, Modal, Form, Input, Popconfirm, } from 'antd'
import { DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import axios from 'axios'
const EditableContext = React.createContext(null);
const { confirm } = Modal
export default function NewsCategory() {
    const [dataSource, setdataSource] = useState([])
    useEffect(() => {
        query()
    }, [])

    const query = () => {
        axios.get('/categories').then(res => {
            setdataSource(res.data)
        })
    }
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '栏目名称',
            dataIndex: 'title',
            key: 'title',
            onCell: (record) => ({
                record,
                editable: true,
                dataIndex: 'title',
                title: '栏目名称',
                handleSave,
            }),
        },
        {
            title: '操作',
            render: (item) => {
                return <div>
                    <Button onClick={() => confirmMethod(item)} style={{ margin: '4px' }} type="danger" shape="circle" icon={<DeleteOutlined />} />
                </div >
            }
        },
    ];
    const handleSave = (item) => {
        axios.patch(`/categories/${item.id}`, { ...item }).then(res => {
            query()
        })
    }

    const confirmMethod = (item) => {
        confirm({
            title: '您确定要删除掉吗',
            icon: <ExclamationCircleOutlined />,
            content: '一旦删除将不可恢复',
            onOk() {
                deleteReady(item)
            },
            onCancel() {

            },
        });
    }
    const deleteReady = (item) => {
        axios.delete(`/categories/${item.id}`).then(() => {
            query()
        })
    }
    const EditableRow = ({ index, ...props }) => {
        const [form] = Form.useForm();
        return (
            <Form form={form} component={false}>
                <EditableContext.Provider value={form}>
                    <tr {...props} />
                </EditableContext.Provider>
            </Form>
        );
    };
    const EditableCell = ({
        title,
        editable,
        children,
        dataIndex,
        record,
        handleSave,
        ...restProps
    }) => {
        const [editing, setEditing] = useState(false);
        const inputRef = useRef(null);
        const form = useContext(EditableContext);
        useEffect(() => {
            if (editing) {
                inputRef.current.focus();
            }
        }, [editing]);
        const toggleEdit = () => {
            setEditing(!editing);
            form.setFieldsValue({
                [dataIndex]: record[dataIndex],
            });
        };
        const save = async () => {
            try {
                const values = await form.validateFields();
                toggleEdit();
                handleSave({
                    ...record,
                    ...values,
                });
            } catch (errInfo) {
                console.log('Save failed:', errInfo);
            }
        };
        let childNode = children;
        if (editable) {
            childNode = editing ? (
                <Form.Item
                    style={{
                        margin: 0,
                    }}
                    name={dataIndex}
                    rules={[
                        {
                            required: true,
                            message: `${title} is required.`,
                        },
                    ]}
                >
                    <Input ref={inputRef} onPressEnter={save} onBlur={save} />
                </Form.Item>
            ) : (
                <div
                    className="editable-cell-value-wrap"
                    style={{
                        paddingRight: 24,
                    }}
                    onClick={toggleEdit}
                >
                    {children}
                </div>
            );
        }
        return <td {...restProps}>{childNode}</td>;
    };

    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    return (
        <div>
            <Table
                components={components}
                dataSource={dataSource} columns={columns} pagination={{
                    pageSize: 10
                }} rowKey={(item) => item.id} />
        </div>
    )


}
